from watchdog.observers import Observer
from watchdog.events import *
import time
import os
from ftplib import FTP

sourcepath = '//10.28.17.90/wpf_m3/'
ftp = FTP()
ftp.set_debuglevel(2)
ftp.connect('10.10.34.51')
ftp.login('spc', 'nmcspc')

class FileEventHandler(FileSystemEventHandler):
    def __init__(self):
        FileSystemEventHandler.__init__(self)

    def on_created(self, event):
        print(event.src_path)
        transfor(event.src_path)
        return event.src_path

    def on_modified(self, event):
        print(event.src_path)
        transfor(event.src_path)
        return event.src_path


def transfor(source_path):
    # SEVP_NMC_CSPB_SFER_EVWP_ACHN_L10_P9_YYYYMMDDHHMMFFFB0.TXT
    path0 = source_path.replace('\\', '/')
    path_split = path0.split('/')
    if path_split[6] in ['100', '150', '200', '250', '300', '600', '900', '1000', '1500', '3000']:
        if '.txt' in path_split[-1]:
            Lcode = str(int(int(path_split[6]) / 10))
            if 'ROBS' in source_path:
                type0 = 'B0'
            elif 'HOBS' in source_path:
                type0 = 'D0'
            elif 'OOBS' in source_path:
                type0 = '01'
            ymdhm = path_split[-1][:12]
            rename = 'SEVP_NMC_CSPB_SFER_EVWP_ACHN_L' + Lcode + '_P9_' + ymdhm + '000' + type0 + '.TXT'
            if os.path.exists(path0):
                ftp.storbinary('STOR ' + '/' + rename, open(path0, 'rb'))


if __name__ == "__main__":
    observer = Observer()
    event_handler = FileEventHandler()
    observer.schedule(event_handler, sourcepath, True)
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()
